//
//  PageScrollView.m
//  ZzzzyManProject
//
//  Created by mac on 16/2/25.
//  Copyright © 2016年 ZzzzyMan@. All rights reserved.
//

#import "PageScrollView.h"
#import "ImageModel.h"
#import "imageViewCell.h"
#import <MBProgressHUD.h>
#import <AVQuery.h>
#import "ZyNetWorkTools.h"

@interface PageScrollView() <UICollectionViewDataSource,UICollectionViewDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView * collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout * flowLayout;
@property (weak, nonatomic) IBOutlet UIPageControl * pageControl;
@property (nonatomic,strong) NSArray * imageViewArr;
@property (nonatomic,strong) NSTimer * timer;
@property (nonatomic,strong) MBProgressHUD * hud;

@end

@implementation PageScrollView


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
   
    self = [[[NSBundle mainBundle] loadNibNamed:@"PageScrollView" owner:nil options:nil] lastObject];
   
    self.frame = CGRectMake(0, 0, 375, 344);
   
    [self initCollectionView];
    
    [self initTimer];
    
    //设置初始位置在第二组
    NSIndexPath * indexPath = [NSIndexPath indexPathForItem:0 inSection:1];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:YES];

    return self;
}

#pragma mark - 初始化计时器
- (void)initTimer {

    self.timer = [NSTimer timerWithTimeInterval:3.5 target:self selector:@selector(cycleScroll) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

#pragma mark - 计时器执行方法
- (void)cycleScroll {
    
    int imageNumber = self.collectionView.contentOffset.x / self.bounds.size.width;
    int index = imageNumber % self.imageViewArr.count;
    
    //当执行完翻页时,回调执行(让cell始终是第一组)
     [UIView animateWithDuration:0.7 animations:^{
         
         CGPoint offset = self.collectionView.contentOffset;
         offset.x += self.bounds.size.width;
         [self.collectionView setContentOffset:offset animated:YES];
         self.pageControl.currentPage = index+1;
         
         if (index==3) {
             self.pageControl.currentPage = 0;
         }
         
     } completion:^(BOOL finished) {
         
         if (index==3) {
             NSIndexPath * indexPath = [NSIndexPath indexPathForItem:0 inSection:1];
             [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
         }
     }];
    
}



#pragma mark - 初始化CollectionView
- (void)initCollectionView {
    
    //设置flowlayout
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    //设置collectionView
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    //注册cell 通过xib
    [self.collectionView registerNib:[UINib nibWithNibName:@"imageViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"imageCell"];
    
    //设置itemSize
    self.flowLayout.itemSize = self.collectionView.bounds.size;
}

#pragma mark - 数据源代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * identifier = @"imageCell";
    imageViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [cell sizeToFit];
    ImageModel * model = self.imageViewArr[indexPath.item];
    cell.model = model;

    return cell;
}

#pragma mark - 当滑动减速的通过偏移量计算是第几张图片
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    int imageNumber = scrollView.contentOffset.x / self.bounds.size.width;
    int index = imageNumber % self.imageViewArr.count;
    NSIndexPath * indexPath = [NSIndexPath indexPathForItem:index inSection:1];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
    self.pageControl.currentPage = index;
}

#pragma mark - 当开始滑动屏幕的时候,停止计时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.timer invalidate];
}

#pragma mark - 当停止滑动屏幕的时候,开始计时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self initTimer];

}

#pragma mark - 懒加载
- (NSArray *)imageViewArr {
    if (!_imageViewArr) {
        
        //从网络中获取数据
        [ImageModel imageArrSuccessBlock:^(NSArray *array) {

            _imageViewArr = array;
            [self.collectionView reloadData];

            
        } errorBlock:^(NSError *error) {
            
//            //当数据加载不到,提示检查网络
//            self.hud = [[MBProgressHUD alloc] initWithView:self.superview];
//            [self.superview addSubview:self.hud];
//            self.hud.labelText = @"请检查网络";
//            self.hud.mode = MBProgressHUDModeCustomView;
//            self.hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"x"]];
//            [self.hud showAnimated:YES whileExecutingBlock:^{
//                sleep(2);
//            } completionBlock:^{
//                [self.hud removeFromSuperview];
//                [self.timer invalidate];
//            }];
            
        }];
          
    }
    return _imageViewArr;
}
@end
